package com.cn.aam.checaiduo.ui.homepage.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.baoyz.widget.PullRefreshLayout;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.RetrofitHome;
import com.cn.aam.checaiduo.backend.observer.OnRequestListV2Listener;
import com.cn.aam.checaiduo.backend.rx.RxSchedulers;
import com.cn.aam.checaiduo.base.BaseFragment;
import com.cn.aam.checaiduo.base.ToolBarManager;
import com.cn.aam.checaiduo.base.adapter.delegator.RecyclerViewDelegatorV2;
import com.cn.aam.checaiduo.base.web.NormalWebActivity;
import com.cn.aam.checaiduo.base.web.RedToolbarWebActivity;
import com.cn.aam.checaiduo.bean.BannerB;
import com.cn.aam.checaiduo.bean.ProductItemB;
import com.cn.aam.checaiduo.bean.base.PageB;
import com.cn.aam.checaiduo.center.PopupWindowCenter;
import com.cn.aam.checaiduo.minterface.OnTabSelectedListener;
import com.cn.aam.checaiduo.ui.arouter.UIRouter;
import com.cn.aam.checaiduo.ui.homepage.adapter.CrowdFundAdapter;
import com.cn.aam.checaiduo.ui.homepage.command.CrowdFundListCommand;
import com.cn.aam.checaiduo.ui.product.ProductDetailActivity;
import com.cn.aam.checaiduo.ui.product.ProductSearchActivity;
import com.cn.aam.checaiduo.utils.MyViewsUtils;
import com.cn.aam.checaiduo.utils.WindowsUtils;
import com.cn.aam.checaiduo.widget.MultiStateView;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.cn.aam.checaiduo.Const.BROADCAST_FRESH_INVEST_LIST;


/**
 * @author 微木森林
 * @time 2017/7/21 下午1:39
 * @description 投资列表
 * @remark
 */
public class InvestFragment extends BaseFragment implements OnTabSelectedListener {
    //众筹产品类别，1-浮动收益，2-固定收益，默认包括全部类别
    public static final String FLOATING_INCOME = "1";
    public static final String FIXED_INCOME = "2";


    @BindView(R.id.id_recyclerview)
    RecyclerView idRecyclerview;
    @BindView(R.id.id_swipe)
    PullRefreshLayout idSwipe;
    @BindView(R.id.id_multistateview)
    MultiStateView idMultistateview;
    @BindView(R.id.iv_fbtn_up)
    ImageView ivFbtnUp;

    private View headerVeiw;//头部视图
    private ConvenientBanner<BannerB> convenientBanner;//广告banner
    private SegmentTabLayout tabLayout;

    //列表
    private CrowdFundListCommand mCommand;
    private CrowdFundAdapter mAdapter;
    private RecyclerViewDelegatorV2<ProductItemB> mDelegator;

    private PaySuccessReceiver paySuccessReceiver;


    public static InvestFragment newInstance() {
        InvestFragment instance = new InvestFragment();
        return instance;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_invest;
    }


    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        MyViewsUtils.hideAllViews(ivFbtnUp);
        registerRecevier();
        initToolBar();
        initHeader();

    }

    private void registerRecevier() {
        paySuccessReceiver = new PaySuccessReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BROADCAST_FRESH_INVEST_LIST);
        mActivity.registerReceiver(paySuccessReceiver, filter);
    }


    /**
     * @description 初始化ToolBar
     */
    private void initToolBar() {
        ToolBarManager.with(mActivity, WMContent)
                .setTitle("专享产品")
                .setBackgroundColor(R.color.colorPrimary)
                .setLeftMenuIconRes(R.drawable.ic_nav_product_filter)
                .setLeftMenuIconClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PopupWindowCenter.getInstance()
                                .showProductListPopupWindow(mActivity, WMContent, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        popupwindowClick(v);
                                    }
                                });
                    }
                })
                .setRightMenuIconRes(R.drawable.ic_nav_search)
                .setRightMenuIconClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(ProductSearchActivity.newInstance(mActivity));
                        mActivity.overridePendingTransition(R.anim.slide_in_from_top, 0);
                    }
                })
                .setOnclickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (MyViewsUtils.isFastDoubleClick())
                            mDelegator.smoothScrollToPosition(0);
                    }
                });
    }

    /**
     * @param v
     * @description popupWindow的点击事件
     */
    private void popupwindowClick(View v) {
        switch (v.getTag().toString()) {
            case "all":
                mCommand.setType(null);
                break;
            case "raise"://募集中
                mCommand.setType("crowdfunding");
                break;
            case "carry"://气息中
                mCommand.setType("saling");
                break;
            case "back"://已回款
                mCommand.setType("rewarded");
                break;
        }

        mDelegator.beginHeaderRefreshing();
    }


    /**
     * @description 初始化头部
     */
    private void initHeader() {
        headerVeiw = LayoutInflater.from(mActivity).inflate(R.layout.list_header_crowd_fund, null);
        initBanner();
        initTabLayout();
    }


    /**
     * @description 初始化Banner
     */
    private void initBanner() {
        convenientBanner = (ConvenientBanner) headerVeiw.findViewById(R.id.banner_ad);
        MyViewsUtils.hideAllViews(convenientBanner);
        //计算比例   272 / 750
        int bannerWidth = WindowsUtils.getScreenWidth(mActivity);
        int bannerHeight = bannerWidth * 272 / 750;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, bannerHeight);
        convenientBanner.setLayoutParams(params);
        getBannerInfo();
    }

    private void getBannerInfo() {
        RetrofitHome.getInstance()
                .getInternalApi()
                .getBannerList(null)
                .compose(RxSchedulers.<PageB<BannerB>>toMain())
                .subscribe(new OnRequestListV2Listener<BannerB>(mActivity) {
                    @Override
                    protected boolean isShowProgressBar() {
                        return false;
                    }

                    @Override
                    public void onNext(PageB<BannerB> value) {
                        super.onNext(value);
                        List<BannerB> data = value.getData();
                        if (data != null && data.size() > 0) {
                            MyViewsUtils.showAllViews(convenientBanner);
                            showBanner(data);
                            //等待banner获取到数据在请求
                            initRecyclerView();
                        }
                    }
                });
    }


    //显示轮播
    private void showBanner(final List<BannerB> dataList) {
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, dataList);
        convenientBanner.setPageIndicator(new int[]{R.drawable.ic_indicator, R.drawable.ic_indicator_focus});
        convenientBanner.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
        convenientBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                BannerB item = dataList.get(position);
                if (TextUtils.isEmpty(item.getLink())) return;
                UIRouter.getInstance().getWeb().openWebPage(mActivity, item.getLink(), "详情");
            }
        });
        convenientBanner.startTurning(4000);
    }


    //轮播所需  协助类
    class NetworkImageHolderView implements Holder<BannerB> {
        ImageView imageView;

        @Override
        public View createView(Context context) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.banner_item_home, null);
            imageView = (ImageView) view.findViewById(R.id.imageView);
            return view;
        }

        @Override
        public void UpdateUI(Context context, int position, BannerB data) {
            Glide.with(mActivity).load(data.getBanner()).asBitmap().centerCrop().placeholder(R.color.black_alpha20).into(imageView);
        }
    }


    /**
     * @description 初始化TabLayout
     */
    private void initTabLayout() {
        tabLayout = (SegmentTabLayout) headerVeiw.findViewById(R.id.tab_layout);
        //tabLayout
        String[] titles = {"浮动收益", "固定收益"};
        tabLayout.setTabData(titles);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                String category = "1";
                if (position == 0)
                    category = FLOATING_INCOME;
                else
                    category = FIXED_INCOME;
                mCommand.setCategory(category);
                mDelegator.beginHeaderRefreshing();

            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }


    /**
     * @description 初始化列表
     */
    private void initRecyclerView() {
        mCommand = new CrowdFundListCommand(FLOATING_INCOME);
        mAdapter = new CrowdFundAdapter(mActivity);
        mDelegator = new RecyclerViewDelegatorV2<>(mActivity, idMultistateview, idSwipe, idRecyclerview, mAdapter, mCommand, true);
        mDelegator.addHeaderView(headerVeiw);
        mDelegator.beginHeaderRefreshing();


        mDelegator.setOnItemClickListener(new RecyclerViewDelegatorV2.OnItemClickListener<ProductItemB>() {
            @Override
            public void OnItemClick(ProductItemB item, int position) {
                if (MyViewsUtils.isFastDoubleClick()) return;
                startActivity(ProductDetailActivity.newInstance(mActivity, item.getId(), item.getSequence()));
            }
        });
        mDelegator.setOnScrollListener(new RecyclerViewDelegatorV2.onScrollListener() {
            @Override
            public void onLastItem(int position) {
                ivFbtnUp.setVisibility(position >= 31 ? View.VISIBLE : View.GONE);
            }
        });
    }

    /**
     * 返回顶部
     */
    @OnClick(R.id.iv_fbtn_up)
    public void onClickBackToTop() {
        mDelegator.smoothScrollToPosition(0);
    }


    public class PaySuccessReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            mDelegator.refreshCurrentPage();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (convenientBanner != null && hidden)
            convenientBanner.stopTurning();
        else if (convenientBanner != null && !hidden)
            convenientBanner.startTurning(4000);
        //recy
        if (mDelegator != null && !hidden) {
            mCommand.setType(null);
            mDelegator.beginHeaderRefreshing();
        }


    }


    @Override
    public void onTabReSelected() {
        if (mDelegator == null) return;
        mDelegator.smoothScrollToPosition(0);
        mDelegator.beginHeaderRefreshing();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mActivity.unregisterReceiver(paySuccessReceiver);
    }
}
